<?php

namespace app\admin\controller\caijiaku;

use app\admin\library\Auth;
use app\common\controller\Backend;
use Elasticsearch\ClientBuilder;
use fast\Random;
use think\Cache;
use think\Config;
use think\Db;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use OSS\OssClient;
use app\common\library\Upload;
use think\Log;
use app\admin\model\Project;

/**
 * 材价库管理
 *
 * @icon fa fa-circle-o
 */
class MaterialInventory extends Backend
{

    protected $searchFields = 'title,project_name,admin.nickname';
    /**
     * MaterialInventory模型对象
     * @var \app\admin\model\caijiaku\MaterialInventory
     */
    protected $model = null;

    protected $noNeedRight = ['getmarketcategory', 'getMaterialList', 'material', 'import_preview', 'eslist', 'projectlist', 'catelist', 'getsource'];

    protected $excelTitleMapping = [
        'title' => ['名称、型号、规格', '名称', '材料名称', '名称及规格', '名  称', '材 料 名 称'],
        'price' => ['评审价', '市场价', '要约价含税市场价','单价', '单价（元）', '单 价',],
        'unit' => ['单位', '单 位'],
        'own_spec' => ['规格型号'],
        'catename' => ['类别', '分类'],
        'tax' => ['进项税率', '税率', '税率%'],
        'notaxprice' => ['除税市场价', '要约价不含税市场价'],
    ];
    //读excel文件每次限制行数
    protected $excelLimit = 1500;
    protected $childAdminIds = [];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\caijiaku\MaterialInventory;
        $action = strtolower($this->request->action());
        if (in_array($action, ['material', 'index'])) {
            $this->dataLimit = false;
        } else {
            $this->dataLimit = 'auth';
        }
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        $category = (new \app\common\model\caijiatong\Category())->getmarketcategory();
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $wheres = [];
            //排除超管数据
            if(!$this->auth->isSuperAdmin()) {
                //排除超级管理员
                $groupWhere = [
                    'caijiakuid' => CAIJIAKU_ID,
                    'status' => 'normal',
                    'rules' => '*',
                ];
                $groupIds = Db::name('auth_group')->where($groupWhere)->column('id');
                $adminIds = Db::name('auth_group_access')->where(['group_id' => ['in', $groupIds]])->column('uid');
                $wheres['admin_id'] = ['not in', $adminIds];
            }
            $list = $this->model
                    ->with(['admin'])
                    ->where($where)
                    ->where($wheres)
                    ->order($sort, $order)
                    ->paginate($limit);
            foreach ($list as $row) {
                $row->tax = $row->tax > 0 ? $row->tax : '-';
                $row->visible(['id','admin_id','project_name','title','own_spec','unit','price','tax','showdate','areaname','brandname','material_id','material_name','faxnum','govnum','mixnum','inquirynum','source','createtime', 'admin.nickname', 'images', 'lock_code']);
            }

            $result = array('total' => $list->total(), 'rows' => $list->items());

            return json($result);
        }
        $this->assign('category', $category);
        $this->assignconfig('categorylist', $category);
        $this->assignconfig('enableGotocjt', $this->auth->check('caijiaku/material_inventory/gotocjt'));
        return $this->view->fetch();
    }

    public function gotocjt($ids = "")
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        if($ids){
            // if(!$this->auth->cjt_userid){
            //     $this->error(__('请绑定材价通账号'));
            // }
            $this->redirect('https://nbgszkj.cn/release/fabu.html?material_inventory_ids='.$ids);
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));

    }
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $params['year'] = date('Y', strtotime($params['showdate']));
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        // $own_spec_arr = $params['own_spec'] ? json_decode($params['own_spec'], true) : [];
        // $own_spec = '';
        // if ($own_spec_arr) {
        //     foreach ($own_spec_arr as $k => $v) {
        //         $own_spec .= $k . ':' . $v . ';';
        //     }
        //     $own_spec = trim($own_spec, ';');
        // }
        // $params['own_spec'] = $own_spec;
        // $exists = $this->model->where([
        //     'project_name' => $params['project_name'],
        //     'title' => $params['title'],
        //     'own_spec' => $params['own_spec'],
        //     'unit' => $params['unit'],
        //     'showdate' => $params['showdate'],
        // ])->count();
        // if ($exists) { //判断是否有重复的数据 材料名称+规格型号+单位
        //     $this->error('数据重复');
        // }

        $es = ClientBuilder::create()->setHosts($this->eshost)->build();
        $queryModel = new \app\common\model\caijiatong\PriceQuery($es);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            
            //查询价格
            //查询市场价综合价，人工询价
            $data = $this->getESPriceData($params);
            $params = array_merge($params, $data);
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        // $own_spec_arr = $params['own_spec'] ? json_decode($params['own_spec'], true) : [];
        // $own_spec = '';
        // if ($own_spec_arr) {
        //     foreach ($own_spec_arr as $k => $v) {
        //         $own_spec .= $k . ':' . $v . ';';
        //     }
        //     $own_spec = trim($own_spec, ';');
        // }
        // $params['own_spec'] = $own_spec;

        // $exists = $this->model->where([
        //     'id' => ['<>', $row['id']],
        //     'project_name' => $params['project_name'],
        //     'title' => $params['title'],
        //     'own_spec' => $params['own_spec'],
        //     'unit' => $params['unit'],
        //     'showdate' => $params['showdate'],
        // ])->count();
        // if ($exists) { //判断是否有重复的数据 材料名称+规格型号+单位
        //     $this->error('数据重复');
        // }

        $result = false;
        // $es = ClientBuilder::create()->setHosts($this->eshost)->build();
        // $queryModel = new \app\common\model\caijiatong\PriceQuery($es);
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            //查询价格
            //查询市场价综合价，人工询价
            $data = $this->getESPriceData($params);
            $params = array_merge($params, $data);
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function eslist()
    {
        $this->request->filter(['strip_tags', 'trim']);
        $id = $this->request->request('id');
        $type = $this->request->request('type');
        if (!$this->request->isAjax()) {
            $this->assignconfig('type',$type);
            return $this->view->fetch();
        }
        //设置过滤方法
        
        // $page = $this->request->request('page/d', 1);
        $offset = $this->request->request('offset/d', 0);
        $limit = $this->request->request('limit/d', 20);
        $limit = $limit ? : 10;
        $page = ($offset / $limit) + 1;
        $es = ClientBuilder::create()->setHosts($this->eshost)->build();
        $queryModel = new \app\common\model\caijiatong\PriceQuery($es);
        $count = 0;
        $list = [];
        $row = $this->model->get($id);
        if (!$row) {
            return json(['total' => $count, 'rows' => $list]);
        }
        $update = [];
        switch ($type) {
            case 'mix':
                $result = $queryModel->getMixPrice($row, $page, $limit);
                $count = $result['count'];
                if ($page == 1) {
                    $update['mixnum'] = $count;
                }
                if (!empty($result['list'])) {
                    foreach ($result['list'] as $key => $value) {
                        $list[] = [
                            'title' => $value['_source']['title'],
                            'own_spec' =>  $value['_source']['own_spec'],
                            'price' => $value['_source']['taxmarketprice'],
                            'tax' => $value['_source']['tax'],
                            'unit' => $value['_source']['unit'],
                            'showdate' => $value['_source']['showtime'],
                            'areaname' => $value['_source']['areaname'],
                            'brandname' => '',
                            'suppliername' => '',
                            'contactname' =>'',
                            'contactphone' => '',
                        ];
                    }
                }
                break;
            case 'inquiry':
                $result = $queryModel->getInquiryPrice($row, $page, $limit);
                $count = $result['count'];
                if ($page == 1) {
                    $update['inquirynum'] = $count;
                }
                if (!empty($result['list'])) {
                    foreach ($result['list'] as $key => $value) {
                        $list[] = [
                            'title' => $value['_source']['materialname'],
                            'own_spec' => $value['_source']['spec'],
                            'price' => $value['_source']['return'],
                            'tax' => '',
                            'unit' => $value['_source']['unit'],
                            'showdate' => date('Y-m-d', $value['_source']['createtime']),
                            'areaname' => $value['_source']['areaname'],
                            'brandname' => '',
                            'suppliername' => '',
                            'contactname' =>'',
                            'contactphone' => '',
                        ];
                    }
                }
                break;
            case 'gov':
                $result = $queryModel->getGovPrice($row, $page, $limit);
                $count = $result['count'];
                if ($page == 1) {
                    $update['govnum'] = $count;
                }
                if (!empty($result['list'])) {
                    foreach ($result['list'] as $key => $value) {
                        //中国,江西省,南昌市 取南昌市就行
                        $areaname_arr = explode(',', $value['_source']['areaname']);
                        $areaname = array_slice($areaname_arr, 2);
                        $list[] = [
                            'title' => $value['_source']['title'],
                            'own_spec' => $value['_source']['spec'],
                            'price' => $value['_source']['govtaxprice'],
                            'tax' => $value['_source']['tax'],
                            'unit' => $value['_source']['unit'],
                            'showdate' => $value['_source']['year'].'-'.$value['_source']['month'],
                            'areaname' => $areaname,
                            'brandname' => '',
                            'suppliername' => '',
                            'contactname' =>'',
                            'contactphone' => '',
                        ];
                    }
                }
                break;
            default:
                $result = $queryModel->getFaxPrice($row, $page, $limit);
                $count = $result['count'];
                if ($page == 1) {
                    $update['faxnum'] = $count;
                }
                if (!empty($result['list'])) {
                    foreach ($result['list'] as $key => $value) {
                        $own_spec_arr = $value['_source']['own_specjson'] ?? [];
                        $own_spec = '';
                        if ($own_spec_arr) {
                            foreach ($own_spec_arr as $k => $v) {
                                $own_spec .= $v['attrName'] . ':' . $v['attrValue'] . ';';
                            }
                            $own_spec = trim($own_spec, ';');
                        }
                        $list[] = [
                            'title' => $value['_source']['title'],
                            'own_spec' => $own_spec,
                            'price' => $value['_source']['taxmarketprice'],
                            'tax' => $value['_source']['tax'],
                            'unit' => $value['_source']['unit'],
                            'showdate' => $value['_source']['showdate'],
                            'areaname' => $value['_source']['areaname'],
                            'brandname' => $value['_source']['brandname'],
                            'suppliername' => $value['_source']['suppliername'],
                            'contactname' => $value['_source']['contactname'],
                            'contactphone' => $value['_source']['contactphone'],
                        ];
                    }
                }
                break;
        }
        if ($update) {
            $this->model->allowField(true)->save($update, ['id' => $row['id']]);
        }
        
        $return = array('total' => $count, 'rows' => $list);

        return json($return);
    }

    public function trend()
    {

        $id = $this->request->request('id/d', 0);
        if (!$id) {
            $this->error(__('Missing parameters'));
        }
        $info = $this->model->where(['id' => $id, 'caijiakuid' => CAIJIAKU_ID])->find();
        if (!$info) {
            $this->error(__('No Results were found'));
        }
        $ownspec = explode(';', $info['own_spec']);
        $ownspecArr = [];
        foreach ($ownspec as $k => $v) {
            $ownspecArr[] = explode(':', $v);
        }
        $info['own_spec_arr'] = $ownspecArr;
        $list = $this->model->where(['caijiakuid' => CAIJIAKU_ID, 'title' => $info['title'],'own_spec' => $info['own_spec'],'unit' => $info['unit']])->order('showdate asc')->select();
        $return = array('total' => count($list), 'rows' => $list);
        foreach ($list as $k => $v) {
            $userlist[$v['showdate']] = $v['price'];
        }
        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));

        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        return json($return);
    }

    public function import()
    {
        //判断是否有项目库菜单权限
        $project_auth = $this->auth->check('project/index');
        if ($this->request->isPost() == false) {
            $site = Config::get('site');
            $aliossurl = get_addon_config('alioss')['cdnurl'];
            $materialtemplate =  $aliossurl . $site['materialtemplate'];
            $this->view->assign('materialtemplate', $materialtemplate);
            $this->view->assign('project_auth', $project_auth);
            $this->view->assign('excelTitleMapping', $this->excelTitleMapping);
            return $this->view->fetch();
        }
        set_time_limit(0);
        $file = $this->request->request('file', '');
        $rowdata = $this->request->request("row/a", []);
        $project_name = $this->request->request("project_name", '');
        $curtimes = $this->request->request("curtimes/d", 0);//分批量请求
        $lastrow = $this->request->request("lastrow/d", 0);//上次最后读的行数
        if (empty($file)) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        if (empty($project_name)) {
            $this->error(__('Parameter %s can not be empty', 'project_name'));
        }
        $filePath = ROOT_PATH . DS .'public'. $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        if (!file_exists($filePath)) {
            $this->error('文件不存在');
        }

        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }


        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);
        $allColumn = $currentSheet->getHighestDataColumn();
        $allRow = $currentSheet->getHighestRow();
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        $limit = $this->excelLimit;
        $firstnum = $lastrow + 1;
        $imageFilePath = ROOT_PATH . '/public';//图片保存目录
        $fields = [];
        $titleField = $priceField = $unitField = $ownSpecField = $catenameField = $taxField = $notaxpriceField ='';
        $isStart = false;//是否开始读取数据
        $isFirstLine = false;//是否第一行就是表格标题
        //获取标题
        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : trim($val);
            }
            //判断当前行是否列表开始
            if (!$isStart) {
                //判断是否有标题
                $titleMapping = array_intersect($values, $this->excelTitleMapping['title']);
                if (!empty($titleMapping)) {
                    $isStart = true;
                    if (empty($fields)) {
                        $isFirstLine = $currentRow == 1 ? true : false;
                        $fields = $values;
                        //数组交集
                        $titleMapping = array_intersect($fields, $this->excelTitleMapping['title']);
                        $priceMapping = array_intersect($fields, $this->excelTitleMapping['price']);
                        $unitMapping = array_intersect($fields, $this->excelTitleMapping['unit']);
                        $ownSpecMapping = array_intersect($fields, $this->excelTitleMapping['own_spec']);
                        $catenameMapping = array_intersect($fields, $this->excelTitleMapping['catename']);
                        $taxMapping = array_intersect($fields, $this->excelTitleMapping['tax']);
                        $notaxpriceMapping = array_intersect($fields, $this->excelTitleMapping['notaxprice']);
                        if(empty($titleMapping) || (empty($priceMapping) && empty($notaxpriceMapping)) || empty($unitMapping)){
                            $this->error(__('文档识别失败，请确保文档中必须包含：'.implode('/',$this->excelTitleMapping['title']).'，'.implode('/',$this->excelTitleMapping['price']).'，'.implode('/',$this->excelTitleMapping['unit']).'三个必填信息'));
                        }
                        $titleField = array_values($titleMapping)[0];
                        $priceField = array_values($priceMapping)[0];
                        $unitField = array_values($unitMapping)[0];
                        $ownSpecField = !empty($ownSpecMapping) ? array_values($ownSpecMapping)[0] : '';
                        $catenameField = !empty($catenameMapping) ? array_values($catenameMapping)[0] : '';
                        $taxField = !empty($taxMapping) ? array_values($taxMapping)[0] : '';
                        $notaxpriceField = !empty($notaxpriceMapping) ? array_values($notaxpriceMapping)[0] : '';
                        break;
                    }
                } else {
                    continue;
                }
            }
        }
        $data = [];
        //获取项目id
        $project_id = 0;
        if ($project_auth) {
            $project_id = (new Project())->where('project_name', $project_name)->value('id');
        }
        for ($currentRow = $firstnum; $currentRow <= $allRow; $currentRow++) {
            $lastrow = $currentRow;
            if (count($data) >= $limit) {
                break;
            }
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : trim($val);
            }
            $isStart = true;
            
            $temp = array_combine($fields, $values);
            if(empty($temp[$titleField]) || $temp[$titleField] == $titleField || empty($temp[$priceField]) || $temp[$priceField] == $priceField || empty($temp[$unitField]) || $temp[$unitField] == $unitField){
                continue;
            }
            $row = [];
            $row['caijiakuid'] = CAIJIAKU_ID;
            $row['admin_id'] = $this->auth->id;
            $row['project_name'] = $project_name;
            $row['title'] = $temp[$titleField] ?? '';
            $row['own_spec'] = $ownSpecField ? $temp[$ownSpecField] : '';
            $row['unit'] = $temp[$unitField] ?? '';
            $row['price'] = $temp[$priceField] ?? 0;
            $row['brandname'] = $temp['品牌'] ?? '';
            $row['areaname'] = $temp['地区'] ?? '';
            $row['remark'] = $temp['备注'] ?? '';
            $row['suppliername'] = $temp['供应商'] ?? '';
            $row['contactname'] = $temp['联系人'] ?? '';
            $row['contactphone'] = $temp['联系电话'] ?? '';
            $row['tax'] = $taxField ? $temp[$taxField] : 0;
            $row['catename'] = $catenameField ? $temp[$catenameField] : '主材';
            $row['showdate'] = $temp['报价日期'] ?? date('Y-m-d');
            if(!empty($temp['报价日期'])) {
                // 将Excel日期转换为PHP日期
                $phpDate = Date::excelToTimestamp($row['showdate']);
                $showdate = $phpDate;
                if($showdate > time()){
                    $this->error('第' . $currentRow . '行时间错误，请核对');
                }
                $row['showdate'] = date('Y-m-d', $showdate);
            }
            $row['notaxprice'] = $notaxpriceField ? $temp[$notaxpriceField] : 0;
            $row['project_id'] = $project_id;
            $row['createtime'] = time();
            $row['images'] = '';
            //图片处理
            if(isset($rowdata[$currentRow])){
                $row['images'] = $rowdata[$currentRow]['images'] ?? '';
            }
            if (!empty($row['images'])) {
                $images = '';
                $imageArr = explode(',', $row['images']);
                //上传oss
                foreach ($imageArr as $image) {
                    $res = $this->uploadOss($imageFilePath . $image);
                    if($res['stats'] == 1){
                        $fullUrl = $res['data']['info']['url'];
                        $pathInfo = parse_url($fullUrl);
                        $images .= $pathInfo['path'].',';
                        @unlink($imageFilePath . $image);
                    }
                }
                $row['images'] = rtrim($images, ',');
            }
            //查询市场价综合价，人工询价
            $esdata = $this->getESPriceData($row);
            $row = array_merge($row, $esdata);
            $data[$currentRow] = $row;
        }
        if ($data) {
            $data = array_values($data);
            Db::startTrans();
            try{
                $chunkSize = 200; // 每次插入的数据条数
                $dataChunks = array_chunk($data, $chunkSize); // 将数据分割成小数组
                foreach ($dataChunks as $chunk) {
                    $res = Db::name('material_inventory')->insertAll($chunk); // 分批插入数据
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('成功导入数据:' . count($data) . '条', '', ['lastrow' => $lastrow]);
        } else {
            $this->error('没有数据可导入');
        }
    }

    public function import_preview()
    {
        $file = $this->request->request('marketyulanfile');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        $fields = [];
        $newrowdata = [];
        $titleField = $priceField = $unitField = $ownSpecField = $catenameField = $taxField = $notaxpriceField = '';
        $isStart = false;//是否开始读取数据
        $isFirstLine = false;//是否第一行就是表格标题
        for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : trim($val);
            }
            // 判断当前行是否列表开始
            if (!$isStart) {
                //判断是否有标题
                $titleMapping = array_intersect($values, $this->excelTitleMapping['title']);
                if (!empty($titleMapping)) {
                    $isStart = true;
                    if (empty($fields)) {
                        $isFirstLine = $currentRow == 1 ? true : false;
                        $fields = $values;
                        //数组交集
                        $titleMapping = array_intersect($fields, $this->excelTitleMapping['title']);
                        $priceMapping = array_intersect($fields, $this->excelTitleMapping['price']);
                        $unitMapping = array_intersect($fields, $this->excelTitleMapping['unit']);
                        $ownSpecMapping = array_intersect($fields, $this->excelTitleMapping['own_spec']);
                        $catenameMapping = array_intersect($fields, $this->excelTitleMapping['catename']);
                        $taxMapping = array_intersect($fields, $this->excelTitleMapping['tax']);
                        $notaxpriceMapping = array_intersect($fields, $this->excelTitleMapping['notaxprice']);
                        if(empty($titleMapping) || (empty($priceMapping) && empty($notaxpriceMapping)) || empty($unitMapping)){
                            $this->error(__('文档识别失败，请确保文档中必须包含：'.implode('/',$this->excelTitleMapping['title']).'，'.implode('/',$this->excelTitleMapping['price']).'，'.implode('/',$this->excelTitleMapping['unit']).'三个必填信息'));
                        }
                        $titleField = array_values($titleMapping)[0];
                        $priceField = array_values($priceMapping)[0];
                        $unitField = array_values($unitMapping)[0];
                        $ownSpecField = !empty($ownSpecMapping) ? array_values($ownSpecMapping)[0] : '';
                        $catenameField = !empty($catenameMapping) ? array_values($catenameMapping)[0] : '';
                        $taxField = !empty($taxMapping) ? array_values($taxMapping)[0] : '';
                        $notaxpriceField = !empty($notaxpriceMapping) ? array_values($notaxpriceMapping)[0] : '';
                    }
                } else {
                    continue;
                }
            } else {
                $data = [];
                $temp = array_combine($fields, $values);
                if(empty($temp[$titleField]) || (empty($temp[$priceField]) && empty($temp[$notaxpriceField])) || empty($temp[$unitField])){
                    $isStart = $isFirstLine ? true : false;
                } else {
                    // $data['project_name'] = $temp['项目名称'] ?? '';
                    $data['title'] = $temp[$titleField] ?? '';
                    $data['own_spec'] = $ownSpecField ? $temp[$ownSpecField] : '';
                    $data['unit'] = $temp[$unitField] ?? '';
                    $data['price'] = $temp[$priceField] ?? 0;
                    $data['brandname'] = $temp['品牌'] ?? '';
                    $data['areaname'] = $temp['地区'] ?? '';
                    $data['remark'] = $temp['备注'] ?? '';
                    $data['suppliername'] = $temp['供应商'] ?? '';
                    $data['contactname'] = $temp['联系人'] ?? '';
                    $data['contactphone'] = $temp['联系电话'] ?? '';
                    $data['tax'] = $taxField ? $temp[$taxField] : '';
                    $data['catename'] = $catenameField ? $temp[$catenameField] : '主材';
                    $data['showdate'] = $temp['报价日期'] ?? date('Y-m-d');
                    if(!empty($temp['报价日期'])) {
                        // 将Excel日期转换为PHP日期
                        $phpDate = Date::excelToTimestamp($data['showdate']);
                        $showdate = $phpDate;
                        if($showdate > time()){
                            $this->error('第' . $currentRow . '行时间错误，请核对');
                        }
                        $data['showdate'] = date('Y-m-d', $showdate);
                    }
                    $data['images'] = $temp['图片'] ?? '';
                    $data['notaxprice'] = $temp[$notaxpriceField] ?? '';
                    $data['hang'] = $currentRow;
                    $newrowdata[$currentRow] = $data;
                }
            }
        }
        $imageFilePath1 = ROOT_PATH . '/public';//图片保存目录
        $imageFilePath2 = '/uploads/market/library/'.date('Ymd').'/';
        $imageFilePath = $imageFilePath1 . $imageFilePath2;
        if (!file_exists($imageFilePath)) {
            mkdir($imageFilePath, 0777, true);
        }
        foreach ($currentSheet->getDrawingCollection() as $drawing) {
            list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
            $imageFileName = $drawing->getCoordinates().mt_rand(1000,9999);
            switch ($drawing->getExtension()){
                case 'jpg':
                case 'jpeg':
                    $imageFileName .='.jpg';
                    $source = imagecreatefromjpeg($drawing->getPath());
                    imagejpeg($source, $imageFilePath . $imageFileName);
                    break;
                case 'gif':
                    $imageFileName .='.gif';
                    $source = imagecreatefromgif($drawing->getPath());
                    imagegif($source, $imageFilePath . $imageFileName);
                    break;
                case 'png':
                    $imageFileName .= '.png';
                    $source =imagecreatefrompng($drawing->getPath());
                    imagepng($source, $imageFilePath . $imageFileName);
                    break;
            }
            $newrowdata[$startRow]['images'] .= (!empty($newrowdata[$startRow]['images']) ? ',' : '' ).$imageFilePath2 . $imageFileName;
        }
        if(count($newrowdata)==0){
            $this->error(__('文档识别失败，文档数据为空'));
        }
        $newrowdata = array_values($newrowdata);
        $return = [
            'data' => $newrowdata,
            'count' => count($newrowdata),
            'limit' => $this->excelLimit,
            'batchtimes' => ceil(count($newrowdata) / $this->excelLimit)
        ];
        $this->success('导入成功', '', $return);
    }

    public function import_old()
    {
        if ($this->request->isPost() == false) {
            $site = Config::get('site');
            $aliossurl = get_addon_config('alioss')['cdnurl'];
            $materialtemplate =  $aliossurl . $site['materialtemplate'];
            $this->view->assign('materialtemplate', $materialtemplate);
            return $this->view->fetch();
        }
        set_time_limit(0);
        $file = $this->request->request('file', '');
        $rowdata = $this->request->request("row/a", []);
        $curtimes = $this->request->request("curtimes/d", 0);//分批量请求
        if (empty($file)) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS .'public'. $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        if (!file_exists($filePath)) {
            $this->error('文件不存在');
        }

        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }


        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);
        $allColumn = $currentSheet->getHighestDataColumn();
        $allRow = $currentSheet->getHighestRow();
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);

        $fields = [];
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = trim($val);
            }
        }
        if(!(in_array('项目名称',$fields) && in_array('材料名称',$fields) && in_array('规格型号',$fields) && in_array('单位',$fields) && in_array('评审价',$fields))){
            $this->error(__('文档识别失败，请确保文档中必须包含：【项目名称】，【材料名称】，【规格型号】，【单位】，【评审价】五个必填信息'));
        }

        $data = [];
        $uniqueItems = []; //判断是否有重复的数据
        $count = 0;
        $limit = 1500;
        $firstnum = $curtimes * $limit;
        $imageFilePath = ROOT_PATH . '/public';//图片保存目录
        for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
            if ($currentRow <= $firstnum) {
                continue;
            }
            if ($currentRow > $firstnum + $limit) {
                break;
            }
            $values = [];
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $values[] = is_null($val) ? '' : trim($val);
            }
            $temp = array_combine($fields, $values);
            $row = [];
            //判断是否属于无法识别数据
            if($temp['项目名称'] == '' || $temp['材料名称'] == '' || $temp['规格型号'] == '' || $temp['单位'] == '' || $temp['评审价'] == ''){
                continue;
            }
            // if (empty($temp['项目名称']) || empty($temp['材料名称']) || empty($temp['规格型号']) || empty($temp['单位']) || empty($temp['评审价'])){
            //     $this->error('【项目名称】，【材料名称】，【规格型号】，【单位】，【评审价】必填');
            // }
            if(empty($temp['项目名称'])){$this->error('第'.$currentRow.'行【项目名称】为空');}
            if(empty($temp['材料名称'])){$this->error('第'.$currentRow.'行【材料名称】为空');}
            if(empty($temp['规格型号'])){$this->error('第'.$currentRow.'行【规格型号】为空');}
            if(empty($temp['单位'])){$this->error('第'.$currentRow.'行【单位】为空');}
            if(empty($temp['评审价'])){$this->error('第'.$currentRow.'行【评审价】为空或为0');}
            $row['caijiakuid'] = CAIJIAKU_ID;
            $row['admin_id'] = $this->auth->id;
            $row['project_name'] = $temp['项目名称'] ?? '';
            $row['title'] = $temp['材料名称'] ?? '';
            $row['own_spec'] = $temp['规格型号'] ?? '';
            $row['unit'] = $temp['单位'] ?? '';
            $row['price'] = $temp['评审价'] ?? 0;
            $row['brandname'] = $temp['品牌'] ?? '';
            $row['areaname'] = $temp['地区'] ?? '';
            $row['suppliername'] = $temp['供应商'] ?? '';
            $row['contactname'] = $temp['联系人'] ?? '';
            $row['contactphone'] = $temp['联系电话'] ?? '';
            $row['remark'] = $temp['备注'] ?? '';
            $row['tax'] = !empty((float)$temp['税率%']) ? $temp['税率%'] : '';
            $row['showdate'] = $temp['报价日期'] ?? date('Y-m-d');
            $row['createtime'] = time();
            //图片
            $row['images'] = '';
            // 将Excel日期转换为PHP日期
            $phpDate = Date::excelToTimestamp($row['showdate']);
            $showdate = $phpDate;
            $year = date('Y', $showdate);
            if($showdate > time()){
                $this->error('第' . $currentRow . '行时间错误，请核对');
            }
            $row['year'] = $year;
            $row['showdate'] = date('Y-m-d', $showdate);
            // $itemKey = $row['project_name'].'_'.$row['title'] . '_' . $row['own_spec'] . '_' . $row['unit'].'_'.$row['showdate'];
            // if (in_array($itemKey, $uniqueItems)) { //判断是否有重复的数据 项目名称+材料名称+规格型号+单位+报价日期
            //     continue;
            // }
            // $uniqueItems[] = $itemKey;
            //图片处理
            if(isset($rowdata[$currentRow])){
                $row['images'] = $rowdata[$currentRow]['images'] ?? '';
            }
            if (!empty($row['images'])) {
                $images = '';
                $imageArr = explode(',', $row['images']);
                //上传oss
                foreach ($imageArr as $image) {
                    $res = $this->uploadOss($imageFilePath . $image);
                    if($res['stats'] == 1){
                        $fullUrl = $res['data']['info']['url'];
                        $pathInfo = parse_url($fullUrl);
                        $images .= $pathInfo['path'].',';
                        @unlink($imageFilePath . $image);
                    }
                }
                $row['images'] = rtrim($images, ',');
            }
            //查询市场价综合价，人工询价
            $esdata = $this->getESPriceData($row);
            $row = array_merge($row, $esdata);
            $data[$currentRow] = $row;
        }
        
        if ($data) {
            $data = array_values($data);
            Db::startTrans();
            try{
                $chunkSize = 200; // 每次插入的数据条数
                $dataChunks = array_chunk($data, $chunkSize); // 将数据分割成小数组
                foreach ($dataChunks as $chunk) {
                    $res = Db::name('material_inventory')->insertAll($chunk); // 分批插入数据
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('成功导入数据:' . count($data) . '条');
        } else {
            $this->error('没有数据可导入');
        }
    }

    public function import_preview_old()
    {
        $file = $this->request->request('marketyulanfile');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //加载文件
        if (!$PHPExcel = $reader->load($filePath)) {
            $this->error(__('Unknown data format'));
        }
        $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
        $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
        $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
        $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
        $fields = [];
        for ($currentRow = 1; $currentRow <= 1; $currentRow++) {
            for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                $fields[] = trim($val);
            }
        }
        if(!(in_array('项目名称',$fields) && in_array('材料名称',$fields) && in_array('规格型号',$fields) && in_array('单位',$fields) && in_array('评审价',$fields))){
            $this->error(__('文档识别失败，请确保文档中必须包含：【项目名称】，【材料名称】，【规格型号】，【单位】，【评审价】五个必填信息'));
        }
        try {
            $newrowdata = [];
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : trim($val);
                }
                $data = [];
                $temp = array_combine($fields, $values);
                $data['project_name'] = $temp['项目名称'] ?? '';
                $data['title'] = $temp['材料名称'] ?? '';
                $data['own_spec'] = $temp['规格型号'] ?? '';
                $data['unit'] = $temp['单位'] ?? '';
                $data['price'] = $temp['评审价'] ?? 0;
                $data['brandname'] = $temp['品牌'] ?? '';
                $data['areaname'] = $temp['地区'] ?? '';
                $data['remark'] = $temp['备注'] ?? '';
                $data['suppliername'] = $temp['供应商'] ?? '';
                $data['contactname'] = $temp['联系人'] ?? '';
                $data['contactphone'] = $temp['联系电话'] ?? '';
                $data['tax'] = $temp['税率%'] ?? '';
                $data['showdate'] = $temp['报价日期'] ?? date('Y-m-d');
                //判断是否属于无法识别数据
                if($data['project_name'] == '' || $data['title'] == '' || $data['own_spec'] == '' || $data['unit'] == '' || !$data['price']){
                    continue;
                }
                // 将Excel日期转换为PHP日期
                $phpDate = Date::excelToTimestamp($data['showdate']);
                $showdate = $phpDate;
                if($showdate > time()){
                    throw new \Exception('第' . $currentRow . '行时间错误，请核对');
                }
                $data['showdate'] = date('Y-m-d', $showdate);

                $data['images'] = isset($temp['图片']) ? $temp['图片'] : '';
                $data['hang'] = $currentRow;
                $newrowdata[$currentRow] = $data;
            }
            $imageFilePath1 = ROOT_PATH . '/public';//图片保存目录
            $imageFilePath2 = '/uploads/market/library/'.date('Ymd').'/';
            $imageFilePath = $imageFilePath1 . $imageFilePath2;
            if (!file_exists($imageFilePath)) {
                mkdir($imageFilePath, 0777, true);
            }
            foreach ($currentSheet->getDrawingCollection() as $drawing) {
                list($startColumn, $startRow) = Coordinate::coordinateFromString($drawing->getCoordinates());
                $imageFileName = $drawing->getCoordinates().mt_rand(1000,9999);
                switch ($drawing->getExtension()){
                    case 'jpg':
                    case 'jpeg':
                        $imageFileName .='.jpg';
                        $source = imagecreatefromjpeg($drawing->getPath());
                        imagejpeg($source, $imageFilePath . $imageFileName);
                        break;
                    case 'gif':
                        $imageFileName .='.gif';
                        $source = imagecreatefromgif($drawing->getPath());
                        imagegif($source, $imageFilePath . $imageFileName);
                        break;
                    case 'png':
                        $imageFileName .= '.png';
                        $source =imagecreatefrompng($drawing->getPath());
                        imagepng($source, $imageFilePath . $imageFileName);
                        break;
                }
                $newrowdata[$startRow]['images'] .= (!empty($newrowdata[$startRow]['images']) ? ',' : '' ).$imageFilePath2 . $imageFileName;
            }

            if(count($newrowdata)==0){
                $this->error(__('文档识别失败，文档数据为空'));
            }
            $newrowdata = array_values($newrowdata);
            $return = [
                'data' => $newrowdata,
                // 'count' => count($newrowdata),
                // 'limit' => 1500,
                'batchtimes' => ceil(count($newrowdata) / 1500)
            ];
        }catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('导入成功', '', $return);
    }

    public function downloadlocal($images, $user_id)
    {
        if (empty($images)) return [];
        $imgs = explode(',', $images);
        $imageFilePath1 = ROOT_PATH . '/public';//图片保存目录
        $imageFilePath2 = '/uploads/market/library/'.$user_id.'/'.date('Ymd').'/';
        $imageFilePath = $imageFilePath1 . $imageFilePath2;
        if (!file_exists($imageFilePath)) {
            mkdir($imageFilePath, 0777, true);
        }
        $config = get_addon_config('alioss');
        $domain = $config['cdnurl'];
        $return = [];
        foreach ($imgs as $k => $v) {
            if (empty($v)) continue;
            $filename = basename($domain.$v);
            if(file_exists($imageFilePath.$filename)){
                $return[] = $imageFilePath2.$filename;
                continue;
            }
            if(remoteFileExists($domain.$v)) {
                $filename = basename($domain.$v);
                $res = file_put_contents($imageFilePath.$filename, file_get_contents($domain.$v));
                $return[] = $imageFilePath2.$filename;
            }
        }
        return $return;
    }

    public function getmarketcategory()
    {
        $category = (new \app\common\model\caijiatong\Category())->getmarketcategory();
        return json($category);
    }

    public function getMaterialList()
    {
        $cateid = $this->request->request('cateid');
        $materiallist = (new \app\common\model\caijiatong\Material())->getMaterialList($cateid);
        return json(['code' => 1, 'data' => $materiallist]);
    }

    /**
     * 分类
     */
    public function material()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        $this->model = new \app\common\model\caijiatong\Material();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = array('total' => $list->total(), 'rows' => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    protected function getESPriceData($params)
    {
        $es = ClientBuilder::create()->setHosts($this->eshost)->build();
        $queryModel = new \app\common\model\caijiatong\PriceQuery($es);
        $re = $queryModel->getPriceQuery($params);
        $data = [];
        $data['faxprice'] = !empty($re['fax']['list']) ? (float)$re['fax']['list'][0]['_source']['taxmarketprice'] : 0;
        $data['faxnum'] = $re['fax']['count'] ?? 0;
        $data['mixprice'] = !empty($re['mix']['list']) ? (float)$re['mix']['list'][0]['_source']['taxmarketprice'] : 0;
        $data['mixnum'] = $re['mix']['count'] ?? 0;
        $data['inquiryprice'] = !empty($re['inquiry']['list']) ? (float)$re['inquiry']['list'][0]['_source']['return'] : 0;;
        $data['inquirynum'] = $re['inquiry']['count'] ?? 0;
        $data['govprice'] = !empty($re['gov']['list']) ? (float)$re['gov']['list'][0]['_source']['govtaxprice'] : 0;;
        $data['govnum'] = $re['gov']['count'] ?? 0;
        //获取分类
        $data['material_id'] = !empty($re['fax']['list']) ? $re['fax']['list'][0]['_source']['material_id'] : 1208;
        $data['material_name'] = !empty($re['fax']['list']) ? $re['fax']['list'][0]['_source']['materialname'] : '其他材料';
        return $data;
    }

    protected function uploadOss($file)
    {
        $config = get_addon_config('alioss');
        $oss = new OssClient($config['accessKeyId'], $config['accessKeySecret'], $config['endpoint']);
        $upload = new Upload();
        
        try {
            $fileArr = explode('/', $file);
            $filename = array_pop($fileArr);
            $savekey = '/uploads/market/library/caijiaku/'.$this->auth->id.'/{year}{mon}{day}/{filemd5}{.suffix}';
            //文件绝对路径
            $objectName = $upload->getSavekey($savekey, $file, md5($filename));
            if (empty($objectName) || strpos($objectName, '/') !== 0) {
                throw new \Exception('Invalid objectName');
            }
            $ret = $oss->uploadFile($config['bucket'], ltrim($objectName, '/'), $file);
            Log::write('上传文件到OSS，objectName: ' . $objectName.';ret:'.json_encode($ret, 256));
            //成功不做任何操作
            return ['stats' => 1, 'msg' => '', 'data' => $ret];
        } catch (\Exception $e) {
            Log::write('上传文件到OSS，objectName: ' . $objectName.';err:'. $e->getMessage());
           return ['stats' => 0, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 按项目修改
     *
     * @return void
     */
    public function projectedit()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $projectname = $this->request->post('project_name');
            $showdate = $this->request->post('showdate');
            if (empty($projectname) || empty($showdate)) {
                return json(['code' => 0, 'msg' => '参数不能为空']);
            }
            $year = date('Y', strtotime($showdate));
            $updateData = [
                'showdate' => $showdate,
                'year' => $year,
                'updatetime' => time(),
            ];
            $adminids = $this->auth->getChildrenAdminIds(true);
            $adminids = $adminids ? $adminids : [$this->auth->id];
            $wheres = [
                'admin_id' => ['in', $adminids],
                'project_name' => $projectname,
                'caijiakuid' => CAIJIAKU_ID
            ];
            $res = $this->model->where($wheres)->update($updateData);
            if ($res) {
                return json(['code' => 1, 'msg' => '修改成功']);
            } else {
                return json(['code' => 0, 'msg' => '修改失败']);
            }
        }
        return $this->view->fetch();
    }

    public function projectlist()
    {
        // if ($this->request->request('keyField'))
        // {
            //设置过滤方法
            $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

            //搜索关键词,客户端输入以空格分开,这里接收为数组
            $word = (array)$this->request->request("q_word/a");
            //当前页
            $page = $this->request->request("pageNumber");
            //分页大小
            $pagesize = $this->request->request("pageSize");
            //搜索条件
            $andor = $this->request->request("andOr", "and", "strtoupper");
            //排序方式
            $orderby = (array)$this->request->request("orderBy/a");
            //显示的字段
            $field = $this->request->request("showField");
            //主键
            $primarykey = $this->request->request("keyField");
            //主键值
            $primaryvalue = $this->request->request("keyValue");
            //搜索字段
            $searchfield = (array)$this->request->request("searchField/a");
            //自定义搜索条件
            $custom = (array)$this->request->request("custom/a");
            //如果有primaryvalue,说明当前是初始化传值
            if ($primaryvalue !== null) {
                $where = [$primarykey => ['in', $primaryvalue]];
                $pagesize = 999999;
            } else {
                $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                    $logic = $andor == 'AND' ? '&' : '|';
                    $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                    $searchfield = str_replace(',', $logic, $searchfield);
                    $word = array_filter(array_unique($word));
                    if (count($word) == 1) {
                        $query->where($searchfield, "like", "%" . reset($word) . "%");
                    } else {
                        $query->where(function ($query) use ($word, $searchfield) {
                            foreach ($word as $index => $item) {
                                $query->whereOr(function ($query) use ($item, $searchfield) {
                                    $query->where($searchfield, "like", "%{$item}%");
                                });
                            }
                        });
                    }
                    if ($custom && is_array($custom)) {
                        foreach ($custom as $k => $v) {
                            if (is_array($v) && 2 == count($v)) {
                                $query->where($k, trim($v[0]), $v[1]);
                            } else {
                                $query->where($k, '=', $v);
                            }
                        }
                    }
                };
            }
        // }
        // var_dump($where);
        $adminids = $this->auth->getChildrenAdminIds(true);
        $adminids = $adminids ? $adminids : [$this->auth->id];
        $wheres = [
            'admin_id' => ['in', $adminids],
            // 'caijiakuid' => CAIJIAKU_ID
        ];
        $total = $this->model->where($wheres)->where($where)->group('project_name')->count();
        $list = $this->model->field('id,project_name')->where($wheres)->where($where)->group('project_name')->page($page, $pagesize)->select();
        // echo $this->model->getLastSql();
        return json(['list' => $list, 'total' => $total]);
    }

    public function catelist()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminids = $this->auth->getChildrenAdminIds(true);
        $adminids = $adminids ? $adminids : [$this->auth->id];
        $wheres = [
            'admin_id' => ['in', $adminids],
            // 'caijiakuid' => CAIJIAKU_ID
        ];
        $total = $this->model->where($wheres)->where($where)->group('catename')->count();
        $list = $this->model->field('id,catename')->where($wheres)->where($where)->group('catename')->page($page, $pagesize)->select();
        // echo $this->model->getLastSql();
        return json(['list' => $list, 'total' => $total]);
    }

    public function getsource()
    {
        //设置过滤方法
        $this->request->filter(['trim', 'strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
            $pagesize = 999999;
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                $searchfield = str_replace(',', $logic, $searchfield);
                $word = array_filter(array_unique($word));
                if (count($word) == 1) {
                    $query->where($searchfield, "like", "%" . reset($word) . "%");
                } else {
                    $query->where(function ($query) use ($word, $searchfield) {
                        foreach ($word as $index => $item) {
                            $query->whereOr(function ($query) use ($item, $searchfield) {
                                $query->where($searchfield, "like", "%{$item}%");
                            });
                        }
                    });
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        
        $wheres = [
            'caijiakuid' => CAIJIAKU_ID,
            'status' => 'normal',
        ];
        if(!$this->auth->isSuperAdmin()) {
            //排除超级管理员
            $groupWhere = [
                'caijiakuid' => CAIJIAKU_ID,
                'status' => 'normal',
                'rules' => '*',
            ];
            $groupIds = Db::name('auth_group')->where($groupWhere)->column('id');
            $wheres['group_id'] = ['not in', $groupIds];
        }
        $list = Db::name('admin')->alias('admin')->join('auth_group_access', 'auth_group_access.uid = admin.id')->where($wheres)->where($where)->group('admin.id')->field('admin.id,admin.nickname')->select();
        return json([
            'list' => $list,
            'total' => count($list)
        ]);
    }

}
